package com.mocha.bss.minio.service;

import cn.hutool.core.util.StrUtil;
import com.coffee.minio.MochaMinioTemplate;
import com.coffee.minio.args.MochaBaseArgs;
import com.coffee.minio.args.MochaPutObjectArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@Service
@Slf4j
@AllArgsConstructor
public class FileService {

    private final MochaMinioTemplate mochaMinioTemplate;

    public String upload(MultipartFile file, String bucket) throws Exception {
        if (StrUtil.isBlank(bucket)) {
            bucket = "pinghua";
        }
        String fileName = file.getOriginalFilename();
        InputStream inputStream = file.getInputStream();
        MochaPutObjectArgs mochaPutObjectArgs = new MochaPutObjectArgs();
        mochaPutObjectArgs.setStream(inputStream)
                .setFileName(fileName)
                .setCreator(String.valueOf("1"));
        mochaPutObjectArgs.setBucket(bucket);
        mochaPutObjectArgs.setObject(fileName);

        mochaMinioTemplate.uploadObject(mochaPutObjectArgs);
        String publicURL = mochaMinioTemplate.getPublicURL(
                new MochaBaseArgs().setBucket(bucket).setObject(fileName));

        return publicURL;
    }
}
